package cn.buildoncloud.labor.workermanapplet.business.modules.controller;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.WorkerTeamService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.common.page.Pagination;
import cn.buildoncloud.labor.workermanapplet.dto.TeamInProjectDTO;
import cn.buildoncloud.labor.workermanapplet.dto.WorkerTeamDTO;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import cn.buildoncloud.labor.workermanapplet.util.OCRUtil;
import cn.buildoncloud.labor.workermanapplet.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Description: cn.buildoncloud.labor.workermanapplet.business.modules.controller
 * Created by CuiZibo on 2018/11/6 16:29
 */
@RestController
@RequestMapping("/workerTeam")
public class WorkerTeamController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${webSystemIP}")
    private String webSystemIP;

    @Autowired
    private Dao dao;

    @Autowired
    private WorkerTeamService workerTeamService;

    /**
     * 模糊查询该项目中已经进场的 班组列表
     * @param key
     * @param projectId
     * @return
     */
    @RequestMapping("/fuzzyQueryWorkerTeam")
    public Object fuzzyQueryWorkerTeam(@RequestParam(value = "key", required = false) String key,
                                       @RequestParam(value = "projectId", required = true) String projectId,
                                       @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize
    ) {

        try {
            Pagination pagination = workerTeamService.fuzzyQueryWorkerTeam(projectId, key, pageNumber, pageSize);
            return Result.success(Constant.API_OPERATION_SUCCESS, pagination);
        } catch (Exception e) {
            log.error("workerTeam/fuzzyQueryWorkerTeam: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }

    }

    /**
     * 查询已进场班组的基本信息
     * @param workerTeamId
     * @param projectId
     * @return
     */
    @RequestMapping("/queryWorkerTeamInfoByIdAndProjectId")
    public Object queryWorkerTeamInfoByIdAndProjectId(@RequestParam(value = "workerTeamId", required = true) String workerTeamId,
                                                      @RequestParam(value = "projectId", required = true) String projectId) {

        try {
            TeamInProjectDTO teamInProjectDTO = null;
            if (StringUtil.isNotBlank(workerTeamId)) {
                teamInProjectDTO = workerTeamService.queryWorkerTeamInfoByIdAndProjectId(projectId, workerTeamId);
            }
            return Result.success(Constant.API_OPERATION_SUCCESS, teamInProjectDTO);
        } catch (Exception e) {
            log.error("workerTeam/queryWorkerTeamInfoByIdAndProjectId: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }

    }

    /**
     * 查询已进场班组的详细信息  班组详情 参建项目 班组成员
     * @param workerTeamId
     * @param projectId
     * @param allOrIn
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestMapping("/queryWorkerTeamInfoById")
    public Object queryWorkerTeamInfoById(@RequestParam(value = "workerTeamId", required = true) String workerTeamId,
                                          @RequestParam(value = "projectId", required = true) String projectId,
                                          @RequestParam(value = "allOrIn", required = false) String allOrIn,
                                          @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                          @RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize) {

        try {
            TeamInProjectDTO teamInProjectDTO = null;
            if (StringUtil.isNotBlank(workerTeamId)) {
                teamInProjectDTO = workerTeamService.queryWorkerTeamInfoById(workerTeamId, projectId, allOrIn,pageNumber,pageSize);
            }
            return Result.success(Constant.API_OPERATION_SUCCESS, teamInProjectDTO);
        } catch (Exception e) {
            log.error("workerTeam/queryWorkerTeamInfoById: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }

    }

    /**
     * 班组退场
     * @param workerTeamId
     * @param projectId
     * @param haveBadRecord
     * @param badRecordNote
     * @param evaluate
     * @param score
     * @return
     */
    @RequestMapping("/workerTeamAndOut")
    public Object workerTeamAndOut(@RequestParam(value = "workerTeamId", required = true) String workerTeamId,
                                   @RequestParam(value = "projectId", required = true) String projectId,
                                   //是否有不良记录 true 1 false 0
                                   @RequestParam(value = "haveBadRecord", required = false, defaultValue = "0") boolean haveBadRecord,
                                   @RequestParam(value = "badRecordNote", required = false) String badRecordNote,
                                   @RequestParam(value = "evaluate", required = false) String evaluate,
                                   //星级-评分
                                   @RequestParam(value = "starLevel", required = false) int score) {

        try {

            Map parameterMap = new HashMap<>();
            parameterMap.put("projectId", projectId);
            parameterMap.put("workTeamId", workerTeamId);

            parameterMap.put("haveBadRecord", haveBadRecord);
            parameterMap.put("badRecordNote", badRecordNote);
            parameterMap.put("evaluate", evaluate);
            parameterMap.put("score", score);

            String response = HttpUtil.post(webSystemIP + "/business/workerteam/workerTeamAndOut", parameterMap, 1000 * 10);
            Result result = Json.fromJson(Result.class, response);
            return result;
        } catch (Exception e) {
            log.error("workerTeam/workerTeamAndOut: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }

    }

    /**
     * OCR识别班组长身份证号查询班组信息
     * @param base64File
     * @param projectId
     * @return
     */
    @RequestMapping("/ocrIdCardAndQueryTeamInfo")
    public Object ocrIdCardAndQueryTeamInfo(@RequestParam("base64File") String base64File, @RequestParam("projectId") String projectId) {
        try {
            WorkerTeamDTO workerTeamDTO;
            //ocr获取身份证信息
            Result ocrIdCardResult = OCRUtil.ocrIdCard(base64File);
            if (ocrIdCardResult.getCode() != 0) {
                return ocrIdCardResult;
            }
            Map ocrIdCardResultData = (Map) ocrIdCardResult.getData();
            if (ocrIdCardResultData == null) {
                return Result.error("身份证识别失败，请上传有效的身份证头像面！");
            }
            Map<String, Object> idCardInfoData = (Map<String, Object>) ocrIdCardResultData.get("idCardInfo");
            //通过OCR识别的身份证号去该班组长查询班组信息
            workerTeamDTO = workerTeamService.queryWorkerTeamInfoByIdCardNo((String) idCardInfoData.get("id"));
            if (workerTeamDTO.getTeamId() != null) {
                List<Record> reWorkerTeamAndProjectList = dao.query("bi_re_workerteam_project", Cnd.where("project_id", "=", projectId).and("worker_team_id", "=", workerTeamDTO.getTeamId()));
                if (reWorkerTeamAndProjectList.size() > 0) {
                    Record r = reWorkerTeamAndProjectList.get(0);
                    if (r.getInt("wp_tates") == 0) return Result.error("该班组在本项目中已进场");
                    if (r.getInt("wp_tates") == 1) return Result.error("该班组在本项目中已退场");
                }
            }
            //优化身份证照片
            Result optimizeIdCardDataResult = OCRUtil.optimizeIdCard(base64File);
            if (optimizeIdCardDataResult.getCode() != 0) {
                return optimizeIdCardDataResult;
            }
            Map optimizeIdCardDataData = (Map) optimizeIdCardDataResult.getData();
            if (optimizeIdCardDataData == null) {
                return Result.error("身份证识别失败，请上传有效的身份证头像面！");
            }

            workerTeamDTO.setIdCardImgBase64((String) optimizeIdCardDataData.get("ID_CARD_PHOTO"));
            workerTeamDTO.setIdCardImgPath((String) optimizeIdCardDataData.get("ID_HEAD_PATH"));
            workerTeamDTO.setTeamLeaderName((String) idCardInfoData.get("name"));
            workerTeamDTO.setIdCardNo((String) idCardInfoData.get("id"));

            return Result.success(Constant.API_OPERATION_SUCCESS, workerTeamDTO);

        } catch (Exception e) {
            log.error("workerTeam/ocrIdCardAndQueryTeamInfo: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }

    }

    /**
     * 班组进场接口（包括检验班组是否存在，不存在则创建班组）
     * @param teamId
     * @param companyId
     * @param unitId
     * @param teamLeaderTel
     * @param teamLeaderName
     * @param idCardImgPath
     * @param idCardNo
     * @param materialIs
     * @param projectId
     * @param enterTime
     * @param classTypes
     * @return
     */
    @RequestMapping("/checkWorkerTeamAndEnterProject")
    public Object checkWorkerTeamAndEnterProject(@RequestParam(value = "teamId", required = false) String teamId,
                                                 @RequestParam(value = "companyId", required = false) String companyId,
                                                 @RequestParam("unitId") String unitId,
                                                 @RequestParam("teamLeaderTel") String teamLeaderTel,
                                                 @RequestParam("teamLeaderName") String teamLeaderName,
                                                 @RequestParam("idCardImgPath") String idCardImgPath,
                                                 @RequestParam("idCardNo") String idCardNo,
                                                 @RequestParam("materialIs") String materialIs,

                                                 @RequestParam("projectId") String projectId,
                                                 @RequestParam("enterTime") String enterTime,
                                                 @RequestParam("classTypes") String classTypes) {//格式： 工类id1-工种id1,工类id2-工种id2,工类id3-工种id3

        try {

            //班组进场参数封装
            Map map = new HashMap<>(12);

            map.put("id",teamId);
            map.put("laborServiceCompanyId",companyId);
            map.put("unitId",unitId);
            map.put("teamLeaderTel",teamLeaderTel);
            map.put("teamLeaderName",teamLeaderName);
            map.put("idCardNo",idCardNo);
            map.put("materialIs",materialIs);
            map.put("classTypes", classTypes);
            map.put("idCardPhotoPath", idCardImgPath);
            map.put("projectId",projectId);
            map.put("inDate", enterTime);

            String s = HttpUtil.post(webSystemIP + "/business/workerteam/recordWorkTeamInfoAndEnter", map, 1000 * 30);
            return Json.fromJson(Result.class, s);
        } catch (Exception e) {
            log.error("workerTeam/checkWorkerTeamAndEnterProject: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }
}
